<script setup>
import {computed, onBeforeUnmount, ref, shallowRef} from "vue";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import getConf from "@/views/news-upload/conf";
import {getFileType, addFile, editFile} from '@/api/company-information'
import {uploadFile} from "@/api/common";
import {toast} from "@/hook/toast";
import {Plus} from "@element-plus/icons-vue";

const visible = ref(false)

const formData = ref({
  name: '',
  content: '',
  companyliaotype_id: '',
  images: [],
  files: [],
  id: '',
})
const isEdit = ref(false)


function init(data) {
  const {companyliaotype_id, id, name, files, images, content} = data

  function patchFile(fileStr) {
    if (!fileStr) return []
    const list = fileStr.split(',')
    return list.map((item, index) => {
      return {
        name: `file-${index}`,
        percentage: 100,
        response: {data: {fullurl: item}},
        status: 'success',
        uid: index,
        url: item,
      }
    })
  }

  formData.value = {
    id,
    companyliaotype_id,
    name,
    content: decodeURIComponent(content) || '',
    files: patchFile(files),
    images: patchFile(images)
  }
}

defineExpose({
  open(data) {
    visible.value = true
    initFileTypeList()
    const value = !!data
    isEdit.value = value
    if (!value) return
    init(data)
  }
})
const editorRef = shallowRef()

function handleCreated(editor) {
  editorRef.value = editor
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const typeOption = ref([])

async function initFileTypeList() {
  const resp = await getFileType()
  if (!resp.data) resp.data = []
  const {data} = resp
  typeOption.value = data.map(item => {
    const {id, name} = item
    return {value: id, label: name}
  })
  console.log(resp, 'resp')
}

const toolbarConfig = {}
const getFilename = (src) => {
  const reg = /^[\s\S]+\/static\/([\s\S]+)$/
  const srcExec = reg.exec(src)
  if (srcExec) {
    return srcExec[1]
  }
}
const FILE_LIST = []
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: getConf(
      (src) => {
        const name = getFilename(src)
        if (name) {
          FILE_LIST.push(name)
        }
      },
  ),
}
const fileRef = ref(null)

function uploadChange(ev) {
  const {raw, uid} = ev
  const payload = new FormData()
  payload.set('file', raw)
  uploadFile(payload).then(resp => {
    toast({title: '上传成功'})
    ev.status = 'success'
    ev.response = resp
    formData.value.files.push(ev)
  }).catch(err => {
    console.log(err, 'catch')
    fileRef.value.handleRemove(uid)
  })
}

const rules = computed(() => ({
  name: [
    {
      required: true,
      message: '请输入名称'
    }
  ],
  companyliaotype_id: [
    {
      required: true,
      message: '请输入名称'
    }
  ]
}))

const emits = defineEmits(['success'])


function resetForm() {
  isEdit.value = false
  formData.value = {
    name: '',
    content: '',
    companyliaotype_id: '',
    images: [],
    files: [],
    id: '',
  }
  formRef.value?.resetFields()
}

async function _handle(func, data) {
  const resp = await func(data)
  const {code, msg} = resp
  toast({title: msg, type: code === 1 ? 'success' : 'error'})
  if (code !== 1) return
  emits('success')
  visible.value = false
}

function addHandle() {
  formRef.value.validate(flag => {
    if (!flag) return
    const {files, images, content} = formData.value
    const fileList = files.filter(item => item.status === 'success').map(item => item.response.data.fullurl)
    const imageList = images.filter(item => item.status === 'success').map(item => item.response.data.fullurl)
    const payload = {
      ...formData.value,
      content: encodeURIComponent(content),
      files: fileList.join(','),
      images: imageList.join(',')
    }
    if (!isEdit.value) return _handle(addFile, payload)
    payload.id = formData.value.id
    _handle(editFile, payload)
  })
}

const formRef = ref(null)
</script>

<template>
  <el-drawer
      v-model="visible"
      size="50vw"
      :title="isEdit ? '编辑资料' : '添加资料'"
      @closed="resetForm"
  >
    <div class="full relative">
      <el-scrollbar>
        <el-form :model="formData"
                 label-position="left"
                 ref="formRef"
                 :rules="rules"
                 label-width="80px"
        >
          <el-form-item label="标题" prop="name">
            <el-input placeholder="请输入标题" v-model="formData.name"/>
          </el-form-item>
          <el-form-item label="分类名称" prop="companyliaotype_id">
            <el-select v-model="formData.companyliaotype_id"
                       placeholder="请选择分类名称"
            >
              <el-option v-for="(item,index) in typeOption"
                         :key="index"
                         :value="item.value"
                         :label="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="资料内容" prop="content">
            <div style="border: 1px solid #ccc;width: 100%" v-if="visible">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                       :defaultConfig="toolbarConfig" mode="default"/>
              <Editor style="height: 350px; overflow-y: hidden;" v-model="formData.content"
                      :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated"/>
            </div>
          </el-form-item>
          <el-form-item label="文件" prop="files">
            <el-upload
                :file-list="formData.files"
                class="upload-demo"
                action="/api/common/upload"
                multiple
                :auto-upload="false"
                :on-change="uploadChange"
                ref="fileRef"
            >
              <el-button type="primary">上传文件</el-button>
              <template #tip v-if="!formData.files.length">
                <div class="el-upload__tip">
                  上传文件.
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="图片" prop="images">
            <el-upload
                v-model:file-list="formData.images"
                action="/api/common/upload"
                list-type="picture-card"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <template #footer>
      <el-space>
        <el-button type="primary" @click="addHandle">确认添加</el-button>
      </el-space>
    </template>

  </el-drawer>
</template>

<style scoped lang="scss">
.upload-demo {
  width: 320px;
}
</style>
